package com.book.manager.component;

import com.book.manager.constant.RedisKeyPrefixConst;
import com.book.manager.mapper.BookMapper;
import com.book.manager.model.Book;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;

@Service
public class LoadBookCache implements InitializingBean {
    @Autowired
    private BookMapper dao;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void afterPropertiesSet() throws Exception {
        loadHotBook2Cache();
    }

    public void loadHotBook2Cache() {
        if (!redisTemplate.hasKey(RedisKeyPrefixConst.FLASH_PROMOTION_PRODUCT_KEY)) {
            List<Book> promotion = dao.listAllBook();
            if (!ObjectUtils.isEmpty(promotion)) {
                promotion.stream().forEach(item -> {
                    redisTemplate.opsForValue().set(RedisKeyPrefixConst.FLASH_PROMOTION_PRODUCT_KEY + String.valueOf(item.getBookId()), item);
                });
            }
        }
    }
}
